<template>
  <div class="employees-container">
    <div class="app-container">
      <page-tools>
        <template #left>
          <span>总记录数: {{ total }} 条</span>
        </template>
        <template #right>
          <el-button
          v-allow="'import'"
            type="warning"
            size="small"
            @click="$router.push('/import')"
            >excel导入</el-button
          >
          <el-button 
          v-allow="'export_excel'"
          type="danger" size="small" @click="handleDownload"
            >excel导出</el-button
          >
          <el-button 
          v-allow="'add'"
          type="primary" size="small" @click="showDialog = true"
            >新增员工</el-button
          >
        </template>
      </page-tools>

      <el-card style="margin-top: 10px">
        <el-table
          :data="list"
          border
          :default-sort="{ prop: 'timeOfEntry', order: 'ascending' }"
        >
          <el-table-column label="序号" type="index" />
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="头像">
          <template #default="{row}">
            <img :src="row.staffPhoto" style="width:100px;height:100px">
          </template>
          </el-table-column>
          <el-table-column label="工号" prop="mobile" sortable />
          <el-table-column label="聘用形式">
            <template #default="{ row }">
              {{ hireTypeFormat(row.formOfEmployment) }}
            </template>
          </el-table-column>
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column label="入职时间" prop="timeOfEntry" sortable />
          <!-- <el-table-column label="账户状态" /> -->
          <el-table-column label="操作" width="280">
            <template #default="{ row }">
              <!-- @click="$router.push(`/employees/detail/${row.id}`) -->
              <el-button
              
                type="text"
                size="small"
                @click="$router.push(`/employees/detail?id=${row.id}`)"
                >查看</el-button
              >
              <el-button type="text" size="small" @click="hAssignRole(row.id)"
                >分配角色</el-button
              >
              <el-button type="text" size="small" @click="hDel(row.id)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row
          type="flex"
          justify="center"
          align="middle"
          style="height: 60px"
        >
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="page"
            :page-sizes="[2, 3, 5, 10]"
            :page-size="size"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
          >
          </el-pagination>
        </el-row>
        <el-dialog title="新增员工" :visible.sync="showDialog" @close="hClose">
          <EmpDialog
            ref="empDialog"
            @success="hSuccess"
            @close="showDialog = false"
          />
        </el-dialog>
        <el-dialog title="分配角色" :visible.sync="roleShowDialog">
          <AssignRole
            :roleId="roleId"
            v-if="roleShowDialog"
            @close="roleShowDialog = false"
          />
        </el-dialog>
      </el-card>
    </div>
  </div>
</template>
<script>
import { getEmployees, delEmployee } from "@/api/employees";
import employeesEnum from "@/constant/employees";
import EmpDialog from "./empDialog.vue";
import AssignRole from "./assignRole.vue";
// [{id:1,value:'正式'},{id:2,value:'非正式'}] ==>>{1:'正式',2:'非正式'}
// const hireType = {};
// employeesEnum.hireType.forEach((item) => {
//   hireType[item.id] = item.value;
// });
const hireType = employeesEnum.hireType.reduce((acc, item) => {
  acc[item.id] = item.value;
  return acc;
}, {});
export default {
  components: {
    EmpDialog,
    AssignRole,
  },
  data() {
    return {
      roleId: "",
      // 弹层 分配
      roleShowDialog: false,
      // 弹层 新增
      showDialog: false,
      // 员工列表数据
      list: [],
      // 分页
      page: 1,
      size: 2,
      // 总数据
      total: 0,
    };
  },
  created() {
    // 渲染列表
    this.loadEmployeeList();
  },
  methods: {
    hAssignRole(id) {
      this.roleId = id;
      this.roleShowDialog = true;
    },
    dataFormat(list) {
      // 1. 根据数据对象的健根据映射关系，得到一个中文的健，放到一个数组中  ---header ['编号', '密码']
      // 2. 将每一个对象的值，存到一个数组中，所有的结果放入到一个大的数组中--data  [["2018-11-30", "总裁办"],[]]
      const map = {
        id: "编号",
        password: "密码",
        mobile: "手机号",
        username: "姓名",
        timeOfEntry: "入职日期",
        formOfEmployment: "聘用形式",
        correctionTime: "转正日期",
        workNumber: "工号",
        departmentName: "部门",
        staffPhoto: "头像地址",
      };

      const one = list[0];
      // 如果list中有数组，才需要生成表头
      if (!one) return; // 没有数据 直接终止
      const headers = Object.keys(one).map((enkey) => {
        return map[enkey];
      });

      // 2. 生成data数据
      const data = list.map((item) => {
        return Object.values(item);
      });
      return { headers, data };
    },
    // 导出execl
    async handleDownload() {
      // 1. 发送请求获取数据
      try {
        const res = await getEmployees(this.page, this.size);
        if (res.code !== 10000) return;
        console.log("res.data.rows", res.data.rows);
        // 2. 需要将获取到的数据转换为excel需要的格式  header data

        // 3. 调用
        const { headers, data } = this.dataFormat(res.data.rows);
        //  import('@/vendor/Export2Excel')  懒加载的方式读取一个文件（模块）返回是一个promise实例对象
        import("@/vendor/Export2Excel").then((excel) => {
          // excel指的是模块对象(文件对象)，就可以直接调用文件中的任何函数或者使用文件中的任何变量  excel.函数名()   || excel.变量
          console.log(excel, "excel");
          //  excel调用export_json_to_excel()
          excel.export_json_to_excel({
            header: headers,
            data,
            filename: this.filename,
            autoWidth: this.autoWidth,
            bookType: this.bookType,
          });
        });
      } catch (error) {
        console.log(error);
      }
    },
    // 删除
    hDel(id) {
      this.$confirm("您确定删除吗?")
        .then(async () => {
          const res = await delEmployee(id);
          this.$message.success(res.message);
          // 当当前页面只剩下一条数据 进行跳转到前一页
          if (this.list.length === 1) {
            this.page--;
            if (this.page <= 0) {
              this.page = 1;
            }
          }
          this.loadEmployeeList();
        })
        .catch((error) => console.log(error));
    },
    // 重置表单
    hClose() {
      this.$refs.empDialog.resetForm();
    },
    // 重新渲染数据关闭弹层
    hSuccess() {
      this.total++;
      const maxpage = Math.ceil(this.total / this.size);
      this.page = maxpage;
      this.loadEmployeeList();
      this.showDialog = false;
    },
    // 判断聘用形式 正式或者非正式
    hireTypeFormat(data) {
      // return employeesEnum.hireType.find((item) => item.id === data).value;
      return hireType[data] || "未知";
    },
    // 分页
    // 控制每页条数
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.page = 1;
      this.size = val;
      this.loadEmployeeList();
    },
    // 控制页码值
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.page = val;
      this.loadEmployeeList();
    },
    // 获取员工列表
    async loadEmployeeList() {
      try {
        const res = await getEmployees(this.page, this.size);
        console.log(res);
        this.list = res.data.rows;
        this.total = res.data.total;
      } catch (err) {
        console.log(err);
        this.$message.error("加载员工数据失败");
      }
    },
  },
};
</script>